/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.wikimark;

import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.wikimark.TestEventListener.TestResult;

/**
 * The WikiMark main class can be used ether in cmd mode or as program component
 * @see #WikiMark(Config)
 * @see #run()
 * 
 * @author Sergey I. Salishev
 */
public final class WikiMark implements Closeable{
	
    private final Config config;
    private final RequestEmitter emitter;
    
	private final ExecutorService serviceExecutor;

    /**
     * @param args cmd string arguments
     * @throws InterruptedException 
     */
    public static void main(final String[] args) throws InterruptedException {
    	ThreadGroup container = new ThreadGroup("WikiMark thread container") {
			@Override
			public void uncaughtException(Thread arg0, Throwable arg1) {
				super.uncaughtException(arg0, arg1);
				System.exit(-1);
			}
    		
    	};
    	Thread main = new Thread(container, new Runnable() {
			public void run() {
	    		try {
	    			mainPlain(args);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
    	});
    	main.start();
    	main.join();
    }
    
	static void mainPlain(String[] args) throws Exception {
    	Config config;
    	try {
			config = new ArgConfig(args);
    	} catch (IllegalArgumentException e) {
    		return;
    	}
    	WikiMark inst = null; 
    	try {
    		inst = new WikiMark(config);
    		inst.run();    		
    	} finally {
    		config.close();
    		if (inst != null) {
    			inst.close();
    		}
    	}				
	}    		

    
    /** 
     * @param config the WikiMark configuration
     */
    public WikiMark(Config config) {
    	this.config = config;
        emitter = new RequestEmitter(config.getConnectivity(), config
				.getDriver(), config.getOutputLogger());
        int[] threadCounts = config.getThreadCounts();
        serviceExecutor = Executors.newFixedThreadPool(1);//threadCounts[threadCounts.length - 1]);
    }
    
    /**
     * Executes the testing procedures according to configuration
     * @throws Exception on unhandled error
     */
    public void run() throws Exception {
    	int[][] density = config.getPageSizeDensity();
    	config.getTestEventListener().onStart();
    	
    	final int[] threadCounts = config.getThreadCounts();
    	
    	final Map<String, Integer> pages = createPages(density,
				threadCounts[threadCounts.length - 1]);

    	for (int threads : threadCounts) {
	    	config.getTestEventListener().onTestSetup(threads);
            test(threads, pages);            
	        config.getTestEventListener().onTestTeardown();
        }
        
    	deletePages(pages);

        config.getTestEventListener().onFinish();

    }
        
    private void test(final int threads, Map<String, Integer> pages)
            throws Exception {
    	
    	final ExecutorService e = Executors.newFixedThreadPool(threads);
    	try {	    		    	
	        for (int i = 0; i < config.getRequestPerPageCount(); i++) {
	        	List<Callable<Integer>> tasks = createPageRequests(pages);
	        	config.getTestEventListener().onTestStart(i);
	            TestResult res = runTasks(e, tasks);
	            config.getTestEventListener().onTestFinish(res);            
	        }
    	} finally {
    		e.shutdown();
    	}
    }

	private List<Callable<Integer>> createPageRequests(
			final Map<String, Integer> pages) {
		
		List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(pages
				.size());
		
		for (final Map.Entry<String, Integer> page : pages.entrySet()) {
			tasks.add((Callable<Integer>) new Callable<Integer>() {
				public Integer call() throws Exception {
					return requestAndCountOutputLength(page.getKey(), page
							.getValue());
				}
			});
		}
		return tasks;
	}

	private int requestAndCountOutputLength(String id, int pageSize) throws IOException {
		Reader out = emitter.request(id);
		int total = 0;
		int prevRead;
		int oneRead = 0;
		char[] buf = new char[8192];
        do {
        	prevRead = oneRead;
        	oneRead = out.read(buf);
        	total += oneRead > 0 ? oneRead : 0;
        } while (oneRead > 0);
        
		if (total < pageSize) {
			if (prevRead > 0) {
				System.err.println(String.valueOf(buf, 0, prevRead));
			}
			throw new IOException("Page " + id + " size " + total + " is too small");
		}
        return total;
	}            

    private void deletePages(Map<String, Integer> 
				pages) throws Exception { 
    	
    	List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(
				pages.size());
    	for (final String id : pages.keySet()) {
    		tasks.add(new Callable<Integer>() {
                public Integer call() throws Exception {
                	savePage(id, "");                  
                    return 0;
                }            
    		});
    	}
    	runTasks(serviceExecutor, tasks);
    }    

    private TestResult runTasks(ExecutorService e, List<Callable<Integer>> tasks)
			throws Exception {
		long output = 0;

		final long start = System.currentTimeMillis();
		List<Future<Integer>> results = e.invokeAll(tasks);
		final long stop = System.currentTimeMillis();

		for (Future<Integer> r : results) {
			output += r.get();
		}
		return new TestResult(stop - start, output);
	}

    private Map<String, Integer> createPages(
			final int[][] pageSizeDensity, int mult) throws Exception {
    	    	
    	final Distribution distr = new Distribution(pageSizeDensity, mult); 
        final Bredogen bred = new Bredogen(config.getDriver(), distr.total);
        String ids[] = bred.getIds();
    	List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(
				ids.length);

		final Map<String, Integer> pages = new HashMap<String, Integer>(
				distr.total);
		
		final Iterator<Integer> sizes = distr.iterator();
    	for (final String id : bred.getIds()) {
    		tasks.add(new Callable<Integer>() {
                public Integer call() throws Exception {
                	final int size = sizes.next();
                	pages.put(id, size);
                    String bredPage = bred.createText(size);
                    savePage(id, bredPage);
                    return 0;
                }            
    		});
    	}
    	runTasks(serviceExecutor, tasks);

        return pages;
    }    

	private void savePage(final String id, String bredPage) throws IOException {
        emitter.emit(id, bredPage);
    }

	public void close() throws IOException {
		serviceExecutor.shutdown();
	}
    

}
